import godebug from '../godebug'

let global = window;

// 重写监s听
const rewriteEventListener = () => {
    if (!window.Element) {
        Element = function() {};
        var __createElement = document.createElement;
        document.createElement = function(tagName) {
            var element = __createElement(tagName);
            if (element == null) { return null; }
            for (var key in Element.prototype)
                element[key] = Element.prototype[key];
            return element;
        }

        var __getElementById = document.getElementById;
        document.getElementById = function(id) {
            var element = __getElementById(id);
            if (element == null) { return null; }
            for (var key in Element.prototype)
                element[key] = Element.prototype[key];
            return element;
        }
    }

    var _HTMLElement = window.HTMLElement || Element;
    var _Element = _HTMLElement.prototype;
    let createElement = document.createElement
    document.onclick = function(e) {
        if (e.target.onclick) {
            godebug.emit('onclick', e);

        }
    }

    let addEventListener = _Element.addEventListener;
    let removeEventListener = _Element.removeEventListener;
    let cache = {};
    if (addEventListener) {
        // 重写监听事件
        _Element.addEventListener = function() {
            addEventListener.apply(this, arguments);
            if (godebug.reportEvent.indexOf(arguments[0]) == -1) {
                return false;
            }
            let name = 'fun' + (+new Date());
            cache[name] = function(params) {
                let type = arguments[0].type;
                godebug.emit(type);

            }
            arguments[1] = cache[name];
            this.setAttribute('godebug', name);
            addEventListener.apply(this, arguments);
        }
        _Element.removeEventListener = function(params) {
            removeEventListener.apply(this, arguments);
            if (godebug.reportEvent.indexOf(arguments[0]) == -1) {
                return false;
            }
            let name = this.getAttribute('godebug');
            arguments[1] = cache[name]
            removeEventListener.apply(this, arguments);
        }
    }

}
// dom解析完毕
const completed = () => {
    // console.log('read')
    godebug.isReady = true;
    godebug.emit('ready');
}

const registerCompleted = () => {
    if (document.readyState === "complete") {
        completed();
    } else if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", completed, false);
    } else {
        document.attachEvent("onreadystatechange", completed);

        // A fallback to window.onload, that will always work
        window.attachEvent("onload", completed);

        // If IE and not a frame
        // continually check to see if the document is ready
        var top = false;

        try {
            top = window.frameElement == null && document.documentElement;
        } catch (e) {}

        if (top && top.doScroll) {
            (function doScrollCheck() {
                if (!godebug.isReady) {

                    try {
                        // Use the trick by Diego Perini
                        // http://javascript.nwbox.com/IEContentLoaded/
                        top.doScroll("left");
                    } catch (e) {
                        return setTimeout(doScrollCheck, 50);
                    }

                    // detach all dom ready events
                    detach();

                    // and execute any waiting functions
                    completed();
                }
            })();
        }
    }
}

function registerError() {
    // type 错误事件类型
    // message 错误信息
    // lineno  行号
    // colno 列号
    // url 文件名
    // stack 堆栈信息
    // timeStamp 错误时间
    // if (global.addEventListener) {
    global.addEventListener('error', function(e) {
            // 主要监控资源加载错误
            // if(e.st)
            if (!e.target.src) {
                return false;
            }
            // _log('a-b=',e.target.src)
            let data = {
                type: e.type,
                message: e.message,
                lineno: e.lineno,
                colno: e.colno,
                url: e.filename,
                // stack:e.error.stack,
                timeStamp: e.timeStamp,
            };
            godebug.emit.call(godebug, 'resourceError', data);
        }, true)
        //  } else
        {
          
            //储存绑定过onerror,要回掉回去
            let _onerror = global.onerror;
            global.onerror = function(msg, fileName, lineno, colno, error) {
                //_log(error)
                // console.log("msg:" + msg)
                // console.log("url:" + url)
                // console.log("line:" + lineno)
                // console.log("col:" + colno)
                // console.log("error:" + error)
                // console.log(JSON.stringify(global.event))
                // console.log('***************************************')
                //  _log(colno)
                if (!colno) {
                    colno = global.event.errorCharacter;
                }
                let data = {
                    type: 'error',
                    name: error && error.name,
                    message: msg,
                    lineno: lineno,
                    colno: colno,
                    fileName: fileName,
                    stack: error && error.stack
                        // timeStamp: 'e.timeStamp',
                };
                // console.log(JSON.stringify(data))
                godebug.emit.call(godebug, 'error', data);
                _onerror && _onerror.apply(this, arguments);
            }
        }

}

function registerRequest() {
    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", function() {
            // M = {
            //     url: global.location.href,
            //     title: document.title
            // }
            //  _log(location.href)
        })
    } else {
        document.attachEvent("onreadystatechange", function() {

            _log('_this.readyState')
                // M = {
                //     url: global.location.href,
                //     title: document.title
                // }
                //   _log( global.location.href)
        });
    }

}

function registerEvent() {
    registerCompleted();
    registerError();
    registerRequest();
}
export default (function() {
    rewriteEventListener();
    registerEvent();
}())